import { Component, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { _HttpClient } from '@delon/theme';
import { FormGroup } from '@angular/forms';
import { SimpleListService } from '@api/simple/service/simpleList.service';
import { SimpleListFormFields } from '@api/simple/model/simpleListFormFields.model';
import { ActivatedRoute } from '@angular/router';
import { SimpleListEditBaseComponent } from './widget/base/base.component';
import { SimpleListEditFieldComponent } from './widget/field/field.component';
import { SimpleListEditFormComponent } from './widget/form/form.component';

@Component({
  selector: 'app-simple-list-edit',
  templateUrl: './edit.component.html',
})
export class SimpleListEditComponent {
  form!: FormGroup;
  record: SimpleListFormFields = { fields: [], form: { fields: [] }, action: { fields: [] } };
  code: String = '';

  @ViewChild('base', { static: false }) simpleListEditBaseComponent!: SimpleListEditBaseComponent;
  @ViewChild('field', { static: false }) simpleListEditFieldComponent!: SimpleListEditFieldComponent;
  @ViewChild('form', { static: false }) simpleListEditFormComponent!: SimpleListEditFormComponent;
  constructor(
    public msgSrv: NzMessageService,
    public http: _HttpClient,
    public simpleListService: SimpleListService,
    public route: ActivatedRoute,
  ) {
    this.route.queryParams.subscribe((params) => {
      this.code = params.code;
      if (this.code) {
        this.simpleListService.findSimpleListFormFieldsByCode(this.code).subscribe((res) => {
          this.record = res;
        });
      }
    });
  }

  save() {
    this.simpleListEditBaseComponent.validate();
    this.simpleListEditFieldComponent.validate();
    this.simpleListEditFormComponent.validate();
    if (
      this.simpleListEditBaseComponent.form.valid &&
      this.simpleListEditFieldComponent.form.valid &&
      this.simpleListEditFormComponent.form.valid
    ) {
      this.record.form!.fields = this.simpleListEditFormComponent.data;
      this.record.fields = this.simpleListEditFieldComponent.data;
      this.simpleListService.saveSimpleListFormFields(this.record).subscribe((res) => {
        this.record = res;
        this.msgSrv.success('保存成功');
      });
    }
  }

  close() {}
}
